"""
FastAPI应用程序主文件
"""
import sys
import os
from pathlib import Path

# 添加项目根目录到Python路径
current_dir = Path(__file__).parent
project_root = current_dir.parent
sys.path.insert(0, str(project_root))

from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles
from contextlib import asynccontextmanager

# 修改为绝对导入
from backend.config import settings
from backend.routes.kafka_routes import router as kafka_router
from backend.routes.log_routes import router as log_router
from backend.routes.websocket_routes import router as websocket_router
from backend.utils.exceptions import KafkaMonitorException
from backend.utils.logger import log_manager

@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用程序生命周期管理"""
    # 启动时的初始化
    log_manager.log_operation(
        operation="SYSTEM_START",
        message="Kafka监控服务启动",
        success=True
    )
    
    yield
    
    # 关闭时的清理
    log_manager.log_operation(
        operation="SYSTEM_STOP",
        message="Kafka监控服务关闭",
        success=True
    )

# 创建FastAPI应用
app = FastAPI(
    title=settings.PROJECT_NAME,
    version=settings.VERSION,
    description="Kafka监控和测试工具",
    lifespan=lifespan
)

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.CORS_ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 全局异常处理器
@app.exception_handler(KafkaMonitorException)
async def kafka_monitor_exception_handler(request: Request, exc: KafkaMonitorException):
    """处理自定义异常"""
    return JSONResponse(
        status_code=400,
        content={
            "success": False,
            "message": exc.message,
            "error_code": exc.error_code,
            "error_detail": str(exc.details) if exc.details else None
        }
    )

@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    """处理全局异常"""
    log_manager.log_operation(
        operation="ERROR",
        message=f"系统错误: {str(exc)}",
        success=False,
        details={
            "url": str(request.url),
            "method": request.method,
            "error": str(exc)
        }
    )
    
    return JSONResponse(
        status_code=500,
        content={
            "success": False,
            "message": "系统内部错误",
            "error_detail": str(exc)
        }
    )

# 添加路由
app.include_router(kafka_router, prefix=settings.API_V1_STR)
app.include_router(log_router, prefix=settings.API_V1_STR)
app.include_router(websocket_router)

# 根路由
@app.get("/")
async def root():
    """根路由"""
    return {
        "message": "Kafka监控工具API",
        "version": settings.VERSION,
        "status": "运行中"
    }

# 健康检查
@app.get("/health")
async def health_check():
    """健康检查"""
    return {
        "status": "healthy",
        "version": settings.VERSION,
        "timestamp": log_manager.logs[-1].timestamp.isoformat() if log_manager.logs else None
    }

# 添加静态文件服务（用于前端）
try:
    app.mount("/", StaticFiles(directory="frontend/dist", html=True), name="static")
except Exception as e:
    print(f"无法挂载静态文件: {e}")

if __name__ == "__main__":
    import uvicorn
    
    uvicorn.run(
        "app:app",
        host=settings.HOST,
        port=settings.PORT,
        reload=True,
        log_level=settings.LOG_LEVEL.lower()
    ) 